//
//  LogInViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/9/20.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import GoogleSignIn
import Foundation
import TKSubmitTransition
import QuartzCore
import SwiftyUserDefaults

class LogInViewController: BaseViewController, UIViewControllerTransitioningDelegate,GIDSignInUIDelegate {
    var btn: TKTransitionSubmitButton!
    var phoneTextField :UITextField!
    var codeTextField :UITextField!
    
    var btnFromNib: TKTransitionSubmitButton!
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad();
//        self.navigationController?.navigationBar.isHidden = true
        self.navigationController?.isNavigationBarHidden = true
        
        GIDSignIn.sharedInstance().clientID = "473248413538-i6sbqruul93j043qgge8bppgg8gkc42e.apps.googleusercontent.com"
        GIDSignIn.sharedInstance().uiDelegate = self
//        GIDSignIn.sharedInstance().signIn()
        makeBaseUI()
        
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(LogInViewController.receiveToggleAuthUINotification(_:)),
                                               name: NSNotification.Name(rawValue: "ToggleAuthUINotification"),
                                               object: nil)
        toggleAuthUI()
    }
    
    //MARK: - PrivateMethods
    func makeBaseUI(){
        let bg = UIImageView(image: UIImage(named: "Login"))
        bg.frame = self.view.frame
        self.view.addSubview(bg)
        let myImageView = UIImageView(image: UIImage(named: "11矢量智能对象@2x"))
        self.view.addSubview(myImageView)
        myImageView.snp.makeConstraints { (make) in
            make.top.equalTo(110)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 64, height: 64))
        }
        
        let backBtn = UIButton(type: .system)
        backBtn.setTitle(XALanguageManager.getString(key: "取消"), for: .normal)
        self.view.addSubview(backBtn)
        backBtn.setTitleColor(UIColor.white, for: .normal)
        backBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        backBtn.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(30)
            make.right.equalTo(self.view).offset(-15)
            make.size.equalTo(CGSize(width: 60, height: 44))
        }
        backBtn.addTarget(self, action: #selector(LogInViewController.backAction1), for: .touchUpInside)
        
        
        let gooleBtn = UIButton(type: .custom)
        
        gooleBtn.setImage(UIImage.init(named: "谷歌-2@2x"), for: .normal)
        gooleBtn.isHidden = true
        self.view.addSubview(gooleBtn)
        gooleBtn.setTitleColor(UIColor.white, for: .normal)
        gooleBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        gooleBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.view).offset(-50)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 30, height: 30))
        }
        gooleBtn.addTarget(self, action: #selector(LogInViewController.mylogIn), for: .touchUpInside)
        
        
        phoneTextField = ZTYTextField(leftView: nil, frame: CGRect(x: 15 , y: 200, width: 90, height: 38), rightView: nil, color: UIColor.white, boardWidth: 0.8, boardRadius: 4)
        self.view.addSubview(phoneTextField)
        phoneTextField.textColor = UIColor.white
        //        phoneTextField.keyboardType = .numberPad
        
        let placeholserAttributes2 = [NSAttributedStringKey.foregroundColor : UIColor.white,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16)]
        phoneTextField.font = UIFont.systemFont(ofSize: 16)
        phoneTextField.keyboardType = .numberPad
        phoneTextField.isUserInteractionEnabled = false
        phoneTextField.attributedPlaceholder = NSAttributedString(string: XALanguageManager.getString(key: "+86"),attributes: placeholserAttributes2)
        phoneTextField.isHidden = true;
        phoneTextField.textAlignment = .center
        //        phoneTextField.borderStyle=UITextBorderStyle.roundedRect
        phoneTextField.layer.borderColor = UIColor.white.cgColor


        phoneTextField = ZTYTextField(leftView: nil, frame: CGRect(x: 15 , y: 200, width: kScreenWidth - 30, height: 38), rightView: nil, color: UIColor.white, boardWidth: 0.8, boardRadius: 4)
        self.view.addSubview(phoneTextField)
        phoneTextField.textColor = UIColor.white
//        phoneTextField.keyboardType = .numberPad
        let placeholserAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16)]
        phoneTextField.font = UIFont.systemFont(ofSize: 16)
//        phoneTextField.keyboardType = .numberPad
        phoneTextField.attributedPlaceholder = NSAttributedString(string: XALanguageManager.getString(key: "请输入用户名"),attributes: placeholserAttributes)
//        phoneTextField.borderStyle=UITextBorderStyle.roundedRect
        phoneTextField.layer.borderColor = UIColor.white.cgColor
        
        codeTextField = ZTYTextField(leftView: nil, frame: CGRect(x: 15 , y: 200 + 53, width: kScreenWidth - 30, height: 38), rightView: nil, color: UIColor.white, boardWidth: 0.8, boardRadius: 4)
        self.view.addSubview(codeTextField)
        codeTextField.isSecureTextEntry = true
        codeTextField.textColor = UIColor.white
        
        let placeholserAttributes1 = [NSAttributedStringKey.foregroundColor : UIColor.white,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 16)]
        codeTextField.font = UIFont.systemFont(ofSize: 16)
        codeTextField.attributedPlaceholder = NSAttributedString(string: XALanguageManager.getString(key:"请输入密码"),attributes: placeholserAttributes1)
        //        phoneTextField.borderStyle=UITextBorderStyle.roundedRect
        codeTextField.layer.borderColor = UIColor.white.cgColor
        
        
        let zhuceBtn = UIButton(type: .system)
        zhuceBtn.setTitle(XALanguageManager.getString(key: "注册"), for: .normal)
        self.view.addSubview(zhuceBtn)
        zhuceBtn.setTitleColor(UIColor.white, for: .normal)
        zhuceBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        zhuceBtn.contentHorizontalAlignment = .left
        zhuceBtn.snp.makeConstraints { (make) in
            make.top.equalTo(codeTextField.snp.bottom).offset(20)
            make.left.equalTo(self.view).offset(15)
            make.size.equalTo(CGSize(width: 120, height: 15))
        }
        
        
        zhuceBtn.addTarget(self, action: #selector(LogInViewController.zhuceAction), for: .touchUpInside)
        
        
        let passwordForgetBtn = UIButton(type: .system)
        passwordForgetBtn.contentHorizontalAlignment = .right
        passwordForgetBtn.setTitle(XALanguageManager.getString(key: "忘记密码"), for: .normal)
        self.view.addSubview(passwordForgetBtn)
        passwordForgetBtn.setTitleColor(UIColor.white, for: .normal)
        passwordForgetBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        passwordForgetBtn.snp.makeConstraints { (make) in
            make.top.equalTo(codeTextField.snp.bottom).offset(20)
            make.right.equalTo(self.view).offset(-15)
            make.size.equalTo(CGSize(width: 120, height: 15))
        }
        passwordForgetBtn.addTarget(self, action: #selector(LogInViewController.backAction), for: .touchUpInside)
        
        

        btn = TKTransitionSubmitButton(frame: CGRect(x: 15, y: 360, width: kScreenWidth - 30, height: 44))
        btn.layer.cornerRadius = 4;
        btn.backgroundColor = UIColor("#297EFB")
        //        btn.frame.bottom = self.view.frame.height - 60
       
        btn.setTitle(XALanguageManager.getString(key: "登录"), for: UIControlState())
        btn.titleLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 14)
        self.view.addSubview(btn)
        btnFromNib = TKTransitionSubmitButton()
        btn.addTarget(self, action: #selector(LogInViewController.onTapButton(_:)), for: UIControlEvents.touchUpInside)
    }
    
    @objc func backAction(){
         self.navigationController?.pushViewController(changePassWordViewController(), animated: true)
    }
    @objc func backAction1(){
        self.dismiss(animated: true) {
            
        }
    }
    
    @objc func onTapButton(_ button: TKTransitionSubmitButton) {
        
        self.phoneTextField.resignFirstResponder()
        self.codeTextField.resignFirstResponder()
        button.isUserInteractionEnabled = false; MyNetwork.request(target: .loginOfPwd(mobile: phoneTextField.text!, password:String().md5(inString: codeTextField.text!)), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            button.isUserInteractionEnabled = true
            
            if needModel.code == 1111{
                let userModel = LogInModel()
                userModel.yy_modelSet(with: (result as AnyObject)["data"] as! [AnyHashable : Any]);
                Defaults[.isLogInKey] = true
                Defaults[.check_Type] = "2"
                Defaults[.userID] = userModel.user_id
                Defaults[.qrCodeUrl] = userModel.secret
                Defaults[.content] = userModel.account
                Defaults[.userPhone] = userModel.mobile;
                Defaults[.nick_name] = userModel.nick_name;
                
                Defaults[.vip_code] = userModel.vip_code;
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "成功"))
               
                button.animate(0.7, CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut), completion: { () -> () in
                    
                    self.dismiss(animated: false, completion: {
                        
                    })
                })
                
                self.view.bringSubview(toFront: self.btnFromNib)
            }else{
                button.isUserInteractionEnabled = true
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "失败"))
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            button.isUserInteractionEnabled = true; self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
    @objc func zhuceAction() {
        self.navigationController?.pushViewController(ConfirmZhuCeViewController(), animated: true)
//        self.navigationController?.pushViewController(ZhuCeViewController(), animated: true)
    }
    // MARK: UIViewControllerTransitioningDelegate
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return TKFadeInAnimator(transitionDuration: 0.5, startingAlpha: 0.8)
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return nil
    }
    //goole
    @objc func signIn(signIn: GIDSignIn!,
                presentViewController viewController: UIViewController!) {
        self.present(viewController, animated: true, completion: nil)
    }
    @objc func toggleAuthUI() {
        if GIDSignIn.sharedInstance().hasAuthInKeychain() {
            // Signed in
            //            signInButton.isHidden = true
            //            signOutButton.isHidden = false
            //            disconnectButton.isHidden = false
        } else {
            //            signInButton.isHidden = false
            //            signOutButton.isHidden = true
            //            disconnectButton.isHidden = true
            //            statusText.text = "Google Sign in\niOS Demo"
        }
    }
    @objc func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
              withError error: Error!) {
        if let error = error {
            print(error)
        } else {
            // Perform any operations on signed in user here.
            let userId = user.userID                  // For client-side use only!
            let idToken = user.authentication.idToken // Safe to send to the server
            let fullName = user.profile.name
            let givenName = user.profile.givenName
            let familyName = user.profile.familyName
            let email = user.profile.email
            // ...
        }
    }
    
    @objc func didTapDisconnect(_ sender: AnyObject) {
        GIDSignIn.sharedInstance().disconnect()
        // [START_EXCLUDE silent]
        
        // [END_EXCLUDE]
    }
    
    @objc func didTapSignOut(_ sender: AnyObject) {
        GIDSignIn.sharedInstance().signOut()
        // [START_EXCLUDE silent]
//        statusText.text = "Signed out."
        toggleAuthUI()
        // [END_EXCLUDE]
    }
    func signInWillDispatch(signIn: GIDSignIn!, error: NSError!) {
//        UIActivityIndicatorView.stopAnimating()
    }
    @objc func mylogIn(){
        let signIn: GIDSignIn = GIDSignIn.sharedInstance()
        
//        GIDSignIn.sharedInstance().signOut()
        
        if (nil != signIn.currentUser) {
            GIDSignIn.sharedInstance().signOut()
//            return
            
        }
        signIn.signIn()
        return
    }
    
    // Present a view that prompts the user to sign in with Google
    
    // Dismiss the "Sign in with Google" view
    func signIn(signIn: GIDSignIn!,
                dismissViewController viewController: UIViewController!) {
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func receiveToggleAuthUINotification(_ notification: NSNotification) {
        if notification.name.rawValue == "ToggleAuthUINotification" {
            self.toggleAuthUI()
            if notification.userInfo != nil {
                guard let userInfo = notification.userInfo as? [String:String] else { return }
                let signIn: GIDSignIn = GIDSignIn.sharedInstance()
                
                googleLogIn(googleid: signIn.currentUser.userID)
            }
            
            
            
            
        }
    }
    
    func googleLogIn(googleid : String) {
        MyNetwork.request(target: .thirdlogin(google_id: googleid, mobile: "", password: "", invite_user_mobile: ""), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                let userModel = LogInModel()
                userModel.yy_modelSet(with: (result as AnyObject)["data"] as! [AnyHashable : Any]);
                Defaults[.isLogInKey] = true
                Defaults[.userID] = userModel.ids
                Defaults[.qrCodeUrl] = userModel.secret
                Defaults[.content] = userModel.account
                Defaults[.userPhone] = userModel.mobile;
                 Defaults[.nick_name] = userModel.nick_name;
                Defaults[.vip_code] = userModel.vip_code;
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "成功"))
                self.dismiss(animated: false, completion: {
                    
                })
                self.view.bringSubview(toFront: self.btnFromNib)
                
                
            }else if needModel.code == 1000{
                var goolgVC = gooleLogInBingPoneViewController()
                goolgVC.googleID = googleid; self.navigationController?.pushViewController(goolgVC, animated: true)
            }else{
                self.navigationController?.view.makeToast(XALanguageManager.getString(key: "失败"))
            }
            
        }) { (error) in
            //kLog(error.localizedDescription)
            self.navigationController?.view.makeToast(error.localizedDescription)
        }
    }
}

